﻿using System.Data;
using System.Data.SqlClient;

namespace DBMock
{
    /// <summary>
    /// 数据库帮助类
    /// </summary>
    public class DBHelper
    {
        /// <summary>
        /// 获取SqlBulkCopy实例
        /// </summary>
        /// <param name="connection">数据库连接</param>
        /// <param name="dt">数据表</param>
        /// <param name="tableName">目标表名</param>
        /// <returns></returns>
        public static SqlBulkCopy GetBulkCopier(SqlConnection connection, DataTable dt, string tableName = null)
        {
            if (connection == null || dt == null)
                return null;

            if (connection.State != ConnectionState.Open)
            { connection.Open(); }

            var copier = new SqlBulkCopy(connection);
            SetBulkCopier(copier, dt, tableName);

            return copier;
        }

        /// <summary>
        /// 设置SqlBulkCopier
        /// </summary>
        /// <param name="dt">数据表</param>
        /// <param name="tableName">目标表名</param>
        public static void SetBulkCopier(SqlBulkCopy copier, DataTable dt, string tableName = null)
        {
            if (copier == null || dt == null)
                return;

            copier.DestinationTableName = tableName ?? "[dbo].[" + dt.TableName + "]";
            copier.BatchSize = dt.Rows.Count;
            copier.NotifyAfter = dt.Rows.Count / 100;
            copier.BulkCopyTimeout = 5000;

            for (int i = 0; i < dt.Columns.Count; i++)
            {
                string columnName = dt.Columns[i].ColumnName;
                copier.ColumnMappings.Add(columnName, columnName);
            }
        }
    }
}
